var Qiniu_UploadUrl = "http://up.qiniu.com";

$(function(){
    showPharmacyList();

    $('#clickToUpload').on('click',function(){
        if($('#uploadImg').hasClass('hidden')){
            $('#uploadImg').removeClass('hidden');
        }else{
            $('#uploadImg').addClass('hidden');
        }
    });

    upload();
});

function showPharmacyList(){
    API.get('pharmacy_list',{manager:API.token},doShowSelect);
}

function doShowSelect(msg,getStatus){
    if(getStatus){
        html = '';
        for(var i=0; i < msg.length; i++){
            html += '<option name="option_phar" value="'+ msg[i].objectId + '">' + msg[i].name + '</option>'
        }
        $('#pharmacy_select').append(html);
        //var ser = document.getElementsByName('option_phar');
        //for(var j=0;j<ser.length;j++){
        //    ser[j].addEventListener('select',chooseOption,false);
        //}
        $('#pharmacy_select').change(function(e){
            $('#choose_phar').val(e.target.value);
        })
    }
}


function upload() {
    var element = document.getElementById("fileUpload");
    if ("\v" == "v") {
        element.onpropertychange = uploadHandle;
    }
    else {
        element.addEventListener("change", uploadHandle, false);
    }
}

function uploadHandle(){
    getUploadToken();
}

var getUploadToken = function(){
    API.api_get('token',{},returnToken);
};

function returnToken(msg,status){
    if(status){
        var token = msg[0];
        if ($("#fileUpload")[0].files.length > 0 && token != "") {
            Qiniu_upload($("#fileUpload")[0].files[0], token, $("#key").val());
        } else {
            console && console.log("form input error");
        }
    }else{
        console.log("获取token失败");
    }
}

var Qiniu_upload = function(f, token, key) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', Qiniu_UploadUrl, true);
    var formData, startDate;
    formData = new FormData();
    if (key !== null && key !== undefined) formData.append('key', key);
    formData.append('token', token);
    formData.append('file', f);
    var taking;
    xhr.upload.addEventListener("progress", function(evt) {
        if (evt.lengthComputable) {
            var nowDate = new Date().getTime();
            taking = nowDate - startDate;
            var x = (evt.loaded) / 1024;
            var y = taking / 1000;
            var uploadSpeed = (x / y);
            var formatSpeed;
            if (uploadSpeed > 1024) {
                formatSpeed = (uploadSpeed / 1024).toFixed(2) + "Mb\/s";
            } else {
                formatSpeed = uploadSpeed.toFixed(2) + "Kb\/s";
            }
        }
    }, false);

    xhr.onreadystatechange = function(response) {
        if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
            var blkRet = JSON.parse(xhr.responseText);
            if(blkRet.key){
                var new_upload = $('#fileUpload').parent().clone();
                $('#fileUpload').parent().empty().addClass('uploadedImg').removeClass('uploadImg')
                    .append('<img src="http://7xlaxq.com1.z0.glb.clouddn.com/' + blkRet.key+'-thumb" onclick="deleteUploaded($(this));">' +
                    '<input type="hidden" value="'+ blkRet.key +'" name="img_key">');
                $('#uploadImg').append(new_upload);
                var new_uploader = document.getElementById('fileUpload');
                new_uploader.addEventListener("change", uploadHandle, false);
            }
        } else if (xhr.status != 200 && xhr.responseText) {

        }
    };
    startDate = new Date().getTime();
    $("#progressbar").show();
    xhr.send(formData);
};

function deleteUploaded(e){
    messageBox('确认去掉该图片吗?','confirm',function(){
        e.parent().remove();
        layer.closeAll();
    });
}

function chooseOption(){
    //e.parent().find('option').removeAttr('selected');
    //e.attr('selected')
    console.log(123123);
}


function confirmPublicPromotion(){

    var name = $('#name').val();
    var pharmacy_select = $('#choose_phar').val();
    var is_top = $('input[name=is_top]').val();
    var content = $('#content').val();
    var url = $('#url').val();
    var images_input = document.getElementsByName('img_key');
    var images = [];
    for(var i=0;i<images_input.length;i++){
        images.push(images_input[i].value);
    }

    var begin_time = $('#begin_time').val();
    var end_time = $('#end_time').val();

    $('.errorTips').addClass('hidden');
    $('.errorTips').eq(3).removeClass('hidden');

    if(!name){
        $('.errorTips').eq(0).removeClass('hidden');
        return;
    }

    if(!content){
        $('.errorTips').eq(1).removeClass('hidden');
        return;
    }

    if(!url){
        $('.errorTips').eq(2).removeClass('hidden');
        return;
    }



    API.api_post('manager/promotion',{manager:API.token,name:name,pharmacy:pharmacy_select,is_top:is_top,begin_time:begin_time,end_time:end_time,content:content,url:url,images:JSON.stringify(images)},publicRes);
}

function publicRes(msg,status){
    if(status){
        messageBox("发布活动成功",'msg');
    }else{
        messageBox("发布失败",'alert');
    }
}




